<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/GPL-3.0
 * @link https://www.gougucms.com
 */

declare (strict_types = 1);

namespace app\finance\controller;

use app\base\BaseController;
use app\finance\model\Invoice as InvoiceList;
use app\finance\validate\InvoiceCheck;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

class Invoice extends BaseController
{
    protected $iType=1;
    protected $title='销售开票单';
    protected $table='invoice';
    protected $tableMx='invoice_detail';
	//我申请的发票
    public function index()
    {
        if (request()->isAjax()) {
			$param = get_params();
			$where = [];
			foreach (["buyCode","name","specs","brand"] as $v ){
			    if (isset($param[$v])&&$param[$v]){
			        $where[]=['md.'.$v,'like','%'.$param[$v].'%'];
                }
            }
            if (isset($param['xsHt'])&&$param['xsHt']){
                $where[]=['sc.orderNum','like','%'.$param['xsHt'].'%'];
            }
			$where[] = ['i.admin_id','=',$this->uid];
			$where[] = ['i.delete_time','=',0];
			$where[] = ['i.iType','=',$this->iType];
			$where[] = ['ind.status','>',-1];
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list=Db::name($this->tableMx)
                ->alias('ind')
                ->leftJoin('invoice i','i.id=ind.inId')
                ->leftJoin('material_dossier md','md.id=ind.mdId')
                ->leftJoin('purveyor p','p.id=i.customer_id')
                ->leftJoin('department d','d.id=i.invoice_subject')
                ->leftJoin('saleContract sc','sc.id=ind.sealcontractId')
                ->leftJoin('saleContract_detail scd','scd.id=ind.sealContractMxId')
                ->leftJoin('admin a','a.id=i.open_admin_id')
                ->where($where)
                ->order('ind.id DESC')
                ->field('ind.*,d.title as subjectName,i.invoice_type,i.type,i.open_time,
                p.name as pName,sc.orderNum as xsHt,md.name as mdName ,md.brand,md.buyCode,md.unit,
                scd.bjNum,scd.bjMoney,ind.amount,a.name as openName')->paginate($rows);
            return table_assign(0, '', $list);
        } else {
            return view();
        }
    }
	
	//待审批的发票
    public function list()
    {
        if (request()->isAjax()) {
			$param = get_params();
			$status = isset($param['status'])?$param['status']:0;
			$user_id = $this->uid;
			//查询条件
			$map1 = [];
			$map2 = [];
			$map1[] = ['', 'exp', Db::raw("FIND_IN_SET('{$user_id}',i.check_admin_ids)")];
			$map1[] = ['i.delete_time','=',0];
			$map1[] = ['i.iType','=',$this->iType];
			$map2[] = ['', 'exp', Db::raw("FIND_IN_SET('{$user_id}',i.flow_admin_ids)")];
			$map2[] = ['i.delete_time','=',0];
			$model = new InvoiceList();
			if($status == 0){
				$list = $model->get_list($param,[$map1,$map2],'or');
			}			
			if($status == 1){
				$list = $model->get_list($param,$map1);
			}
			if($status == 2){
				$list = $model->get_list($param,$map2);
            }	
            return table_assign(0, '', $list);
        } else {
            return view();
        }
    }
	
	public function copy()
    {
        if (request()->isAjax()) {
			$param = get_params();
			$user_id = $this->uid;
			//查询条件
			$map = [];
			//按时间检索
			if (!empty($param['diff_time'])) {
				$diff_time =explode('~', $param['diff_time']);
				$map[] = ['i.create_time', 'between', [strtotime(urldecode($diff_time[0])),strtotime(urldecode($diff_time[1]))]];
			}
			$map[] = ['i.delete_time','=',0];
			$map[] = ['i.check_status', '=', 2];			
			$map[] = ['i.iType', '=', $this->iType];
			$map[] = ['', 'exp', Db::raw("FIND_IN_SET('{$user_id}',i.copy_uids)")];
			$model = new InvoiceList();
			$list = $model->get_list($param,$map);			
            return table_assign(0, '', $list);
        } else {
            return view();
        }
    }
	
	//发票开具
	public function checkedlist()
    {
        if (request()->isAjax()) {
			$param = get_params();
			$where = [];
			if (!empty($param['check_status'])) {
				$where[] = ['i.check_status','=',$param['check_status']];
            }
			else{
				$where[] = ['i.check_status','in',[2,5,10]];
			}
			//按时间检索
			if (!empty($param['diff_time'])) {
				$diff_time =explode('~', $param['diff_time']);
				$where[] = ['i.create_time', 'between', [strtotime(urldecode($diff_time[0])),strtotime(urldecode($diff_time[1]))]];
			}			
			$where[] = ['i.delete_time','=',0];
			$where[] = ['i.iType','=',$this->iType];
			$model = new InvoiceList();
			$list = $model->get_list($param,$where);
            return table_assign(0, '', $list);
        } else {
//			$auth = isAuthInvoice($this->uid);
//			if($auth == 0){
//				return view('../../base/view/common/roletemplate');
//			}
            return view();
        }
    }

    //添加&编辑
    public function add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            $param=$this->param;
            $mx=$param['mx']??[];
            unset($param['mx']);
            if (!$mx){
                return to_assign(1,'请添加明细');
            }
            if (!$param['customer_id']){
                return to_assign(1,'参数有误');
            }
            $mxId=$mx['mxid']??[];
            $mdId=$mx['mdId']??[];
            $amount=$mx['amount']??[];
            $sealcontractId=$mx['sealcontractId']??[];
            $sealContractMxId=$mx['sealContractMxId']??[];
            $countMount=0;
            foreach ($amount as $value){
                $countMount+=$value;
            }
            $param['update_time']=time();
            $id=$this->param['id']??0;
            Db::startTrans();
            try {
                $param['code']=dJBHBySql($this->table,'code',getOrderPrefix($this->controller).date('Ymd'),false,1000);

                if ($id > 0) {
                    Db::name($this->table)->strict(false)->field(true)->update($param);
                    add_log('edit', $param['id'], $param,$this->title);
                } else {
                    $param['admin_id']=$this->uid;
                    $param['did']=$this->did;
                    $param['amount']=$countMount;
                    $param['create_time'] = time();
                    $param['iType'] = $this->iType;
                    $id = Db::name($this->table)->strict(false)->field(true)->insertGetId($param);
                    add_log('add', $id, $this->param,$this->title);
                }
                foreach ($mdId as $key=> $m){
                    $mxData=[
                        'inId'=>$id,
                        'mdId'=>$mdId[$key],
                        'sealcontractId'=>$sealcontractId[$key],
                        'sealContractMxId'=>$sealContractMxId[$key],
                        'amount'=>$amount[$key],
                        'idType'=>$this->iType,
                        'create_time'=>time(),
                        'update_time'=>time()
                    ];
                    if (isset($mxId[$key])&&$mxId[$key]){
                        unset($mxData['create_time']);
                        $mxData['id']=$mxId[$key];
                    }
                    Db::name($this->tableMx)->save($mxData);
                }

                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return to_assign(1,'操作失败:'.$e->getMessage());
            }

            return to_assign();
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            $detail=[];
            $mxList=[];
            if ($id > 0) {

				$detail = Db::name($this->table)->where('id',$id)->find();
				if(empty($detail)){
					throw new \think\exception\HttpException(406, '找不到记录');
				}
				$mxList=Db::name($this->tableMx)
                    ->alias('ind')
                    ->leftJoin('sale_contract_detail scd','scd.id=ind.sealContractMxId')
                    ->leftJoin('material_dossier md','md.id=scd.mdId')
                    ->leftJoin('sale_contract sc','sc.id=scd.orderId')
                    ->where('ind.status','>',-1)
                    ->where('ind.inId','=',$id)
                    ->field("ind.*,scd.bjNum,scd.bjMoney,sc.orderNum as xsHt,md.brand,md.name as mdName,md.specs,md.buyCode,md.unit")
                    ->select();
            }
			$department = $this->did;
			//获取发票审批流程
//			$flows = get_type_department_flows(7,$department);
            View::assign('user', get_admin($this->uid));
            View::assign('id', $id);
//			View::assign('flows', $flows);
            $punterList=Db::name('purveyor')->where('status',1)
                ->where('dw_type',2)->field('id,name')->select();
            View::assign('punterList',$punterList);
            View::assign('detail', $detail);
            View::assign('mxList', $mxList);

            $tag=$this->module.'/'.$this->controller;
            $pTag=strtolower($tag);
            $printTemplateList=getPrintModelList($pTag);
            View::assign('printTemplateList',$printTemplateList);
            return view();
        }
    }

    public function addMx()
    {
        $punterId=$this->param['punterId']??'';
        $sealContractMxIds=$this->param['sealContractMxIds']??'';
        if ($this->request->isPost()){
            $param=$this->param;
            $limit=$this->param['limit']??15;
            $where[]=['sc.punterId','=',$punterId];
            $where[]=['scd.id','not in',$sealContractMxIds];
            $where[]=['sc.tax','>',0];
            foreach (["buyCode","name","specs","brand"] as $v){
                if (isset($param[$v])&&$param[$v]){
                    $where[]=['md.'.$v,'like','%'.$param[$v].'%'];
                }
            }
           $list= Db::name('sale_contract_detail')->alias('scd')
                ->leftJoin('sale_contract sc','sc.id=scd.orderId')
                ->leftJoin('material_dossier md','md.id=scd.mdId')
                ->where($where)
                ->where('scd.type',1)
                ->where('scd.status',4)
                ->field("scd.*,sc.orderNum as xsHt,md.brand,md.name as mdName,md.specs,md.buyCode,md.unit")
                ->paginate($limit);
            return table_assign(0, '', $list);
        }else{

            View::assign('punterId',$punterId);
            View::assign('sealContractMxIds',$sealContractMxIds);
            return view('');
        }
}

    public function removeMx()
    {
        $ids=$this->param['id']??[];
        if (!$ids){
            return to_assign(1,'参数缺失');
        }
        Db::startTrans();
        try {
            Db::name($this->tableMx)
                ->where('id',$ids)->update(['status'=>-1,'deleted'=>time()]);
            add_log('delete', $ids, $this->param,$this->title.'明细');
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }

        return to_assign();
    }
    //查看
    public function view()
    {
        $id = empty(get_params('id')) ? 0 : get_params('id');
		$model = new InvoiceList();
		$detail = $model->detail($id);
		if(empty($detail)){
			throw new \think\exception\HttpException(406, '找不到记录');
		}
//		$flows = Db::name('FlowStep')->where(['action_id'=>$detail['id'],'type'=>3,'sort'=>$detail['check_step_sort'],'delete_time'=>0])->find();
//		$detail['check_user'] = '-';
//		$detail['copy_user'] = '-';
//		$check_user_ids = [];
//		if($detail['check_status'] == 1){
//			if($flows['flow_type']==1){
//				$detail['check_user'] = '部门负责人';
//				$check_user_ids[]=get_department_leader($detail['admin_id']);
//			}
//			else if($flows['flow_type']==2){
//				$detail['check_user'] = '上级部门负责人';
//				$check_user_ids[]=get_department_leader($detail['admin_id'],1);
//			}
//			else{
//				$check_user_ids = explode(',',$flows['flow_uids']);
//				$check_user = Db::name('Admin')->where('id','in',$flows['flow_uids'])->column('name');
//				$detail['check_user'] = implode(',',$check_user);
//			}
//		}
//
//		if($detail['copy_uids'] !=''){
//			$copy_user = Db::name('Admin')->where('id','in',$detail['copy_uids'])->column('name');
//			$detail['copy_user'] = implode(',',$copy_user);
//		}
//		if($detail['file_ids'] !=''){
//			$fileArray = Db::name('File')->where('id','in',$detail['file_ids'])->select();
//			$detail['fileArray'] = $fileArray;
//		}
//
//		if($detail['other_file_ids'] !=''){
//			$fileArrayOther = Db::name('File')->where('id','in',$detail['other_file_ids'])->select();
//			$detail['fileArrayOther'] = $fileArrayOther;
//		}
//
//		$is_check_admin = 0;
//		$is_create_admin = 0;
//		if($detail['admin_id'] == $this->uid){
//			$is_create_admin = 1;
//		}
//		if(in_array($this->uid,$check_user_ids)){
//			$is_check_admin = 1;
//			//当前审核节点详情
//			if($flows['flow_type'] == 4){
//				$check_count = Db::name('FlowRecord')->where(['action_id'=>$detail['id'],'type'=>3,'step_id'=>$flows['id'],'check_user_id'=>$this->uid])->count();
//				if($check_count>0){
//					$is_check_admin = 0;
//				}
//			}
//		}
//
//		$check_record = Db::name('FlowRecord')->field('f.*,a.name,a.thumb')
//			->alias('f')
//			->join('Admin a', 'a.id = f.check_user_id', 'left')
//			->where(['f.action_id'=>$detail['id'],'f.type'=>3])
//			->order('check_time desc')
//			->select()->toArray();
//		foreach ($check_record as $kk => &$vv) {
//			$vv['check_time_str'] = date('Y-m-d H:i', $vv['check_time']);
//			$vv['status_str'] = '提交';
//			if($vv['status'] == 1){
//				$vv['status_str'] = '审核通过';
//			}
//			else if($vv['status'] == 2){
//				$vv['status_str'] = '审核拒绝';
//			}
//			if($vv['status'] == 3){
//				$vv['status_str'] = '撤销';
//			}
//		}
		
//		View::assign('is_create_admin', $is_create_admin);
//		View::assign('is_check_admin', $is_check_admin);
//		View::assign('check_record', $check_record);
		View::assign('detail', $detail);
//		View::assign('flows', $flows);
        View::assign('uid', $this->uid);
        return view();
    }

    //删除
    public function delete()
    {
        $id = get_params("id");
        $status = InvoiceList::where(['id' => $id])->value('check_status');
        if ($status == 2) {
            return to_assign(1, "已审核的发票不能删除");
        }
        if ($status == 3) {
            return to_assign(1, "已开具的发票不能删除");
        }
        $data['delete_time'] = time();
        $data['id'] = $id;
        try {
            Db::name($this->table)->where('id',$id)->update(['status'=>-1,'delete_time'=>time()]);
            Db::name($this->tableMx)->where('inId',$id)->update(['status'=>-1,'deleted'=>time()]);
            add_log('delete', $id,$this->param,$this->title);
        }catch (\Exception $e){
            return to_assign(1, "删除失败");
        }
        return to_assign(0, "删除成功");
    }

    public function onSure()
    {
        $id=$this->param['id']??'';
        if (!$id){
            return to_assign(1,'参数有误');
        }
        $status=Db::name($this->table)->where('id',$id)->value('status');
        if ($status!=1){
            return to_assign(1,'操作有误');
        }
        $mx=Db::name($this->tableMx)->where('status','>',-1)
            ->where('inId',$id)->count();
        if (!$mx){
            return to_assign(1,'操作有误');
        }
        Db::startTrans();
        try {
            $data=[
                'check_admin_id'=>$this->uid,
                'check_time'=>time(),
                'open_admin_id'=>$this->uid,
                'open_time'=>time(),
                'check_status'=>2,
                'status'=>2,

            ];
            Db::name($this->table)->where('id',$id)
                ->update($data);
            Db::name($this->tableMx)->where('status','>',-1)
                ->where('inId',$id)->update(['status'=>2,'update_time'=>time()]);
            add_log('onSure', $id, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败：'.$e->getMessage());
        }
        return to_assign();
    }

    public function printPage($id)
    {
        $id=$this->param['id']??'';
        $info=Db::name($this->table)
            ->alias('iv')
            ->leftJoin('purveyor p','p.id=iv.customer_id')
            ->leftJoin('invoice_subject ins','ins.id=iv.invoice_subject')
            ->where('iv.id',$id)
            ->field('iv.*,p.name as pName,ins.title as invoiceSubjectName')
            ->find();
        $mxList=Db::name($this->tableMx)
            ->alias('ind')
            ->leftJoin('sale_contract_detail scd','scd.id=ind.sealContractMxId')
            ->leftJoin('material_dossier md','md.id=scd.mdId')
            ->leftJoin('sale_contract sc','sc.id=scd.orderId')
            ->where('ind.status','>',-1)
            ->where('ind.inId','=',$id)
            ->field("ind.*,scd.bjNum,scd.bjMoney,sc.orderNum as xsHt,md.brand,md.name as mdName,md.specs,md.buyCode,md.unit")
            ->select();
        $tempMode=Db::name('print_template')
            ->where('id',$info['printTemplate'])
            ->where('status',1)->order('update_time DESC')
            ->limit(1)
            ->find();
        if (!$tempMode){
            echo '<div style="text-align:center;color:red;margin-top:20%;">请选择合同模板</div>';exit;
            exit();
        }

        $data=[
//            'printName'=>'合同打印',
            'printName'=>$tempMode['name'],
            'invoiceSubjectName'=>$info['invoiceSubjectName'],
            'titleType'=>$info['type']==1?"企业":"个人",
            'invoiceType'=>$info['invoice_type']==1?"增值税专用发票":($info['invoice_type']==2?"普通发票":'专业发票'),
            'pName'=>$info['pName'],
        ];
        $detail=[];
        foreach ($mxList as $k=> $ml){

            $detail[]=[
                'k'=>$k+1,
                'brand'=>$ml['brand'],
                'mdName'=>$ml['mdName'],
                'buyCode'=>$ml['buyCode'],
                'specs'=>$ml['specs'],
                'unit'=>$ml['unit'],
                'bjNum'=>$ml['bjNum'],
                'bjMoney'=>$ml['bjMoney'],
                'saleContractOrderNum'=>$ml['xsHt'],
                'amount'=>$ml['amount'],
            ];
        }
        $res=[];
        foreach ($detail as $key=>$v){
            $res[$key]=$v;
        }
        $data['detail']=$res;

        $temp=$tempMode['tplBody']??'';
        View::assign('temp',$temp);
        View::assign('info',json_encode($data,320));
        return view('../../base/view/common/print_page');
    }
}
